package ar.com.jwa.services.impl;

import java.util.Collection;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NonUniqueResultException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.orm.jpa.support.JpaDaoSupport;
import org.springframework.transaction.annotation.Transactional;

import ar.com.jwa.domain.User;
import ar.com.jwa.services.UserLocalService;

public class UserLocalServiceImpl extends JpaDaoSupport implements UserLocalService {

	private EntityManager em;
	
	private static final Log log = LogFactory.getLog(UserLocalServiceImpl.class);
	
	@Transactional
	public void saveUser(User user) {
		log.error("saving user");
		this.getJpaTemplate().persist(user);
	}
	
	
	@SuppressWarnings("unchecked")
	@Override
	public User login(User user) {
		List<User> players = (List<User>)this.getJpaTemplate().find("select U FROM ar.com.jwa.domain.User U where U.email=?1 and U.password =?2",user.getEmail(),user.getPassword().trim());
		return (players.size() == 1) ? players.get(0) : null;
	}

	@Override
	public User getUserById(Long id) {
		User user = this.getJpaTemplate().find(User.class,id);
		if ( user!= null )
			return user;
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Collection<User> findAll() {
		Collection<User> array =(Collection<User>)this.getJpaTemplate().find("select u from ar.com.jwa.domain.User u");
		return array;
	}

	
	@SuppressWarnings("unchecked")
	@Override
	public User getUserByMail(String email) throws Exception {
		
		try {
			
			List<User> list =  (List<User>) this.getJpaTemplate().find("select U FROM ar.com.jwa.domain.User U where U.email like ?1",email);
			
			if (list.size() > 1){
				throw new NonUniqueResultException("Many users with email = " + email + " has found");
			}
			
			User user = (User) list.get(0);
			
			return user;
		
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
		
	}
	
}
